import {handleExpressError} from './api/utils'

global.BUFFET_SERVER = process.env.BUFFET_SERVER || 'http://localhost:8555'
global.BUFFET_API = process.env.API_URL || 'http://vpn.ao22.ru:8081/StolDiplom_KPA/hs/api'

import express from 'express'
import 'express-async-errors'
import bodyParser from 'body-parser'
import cors from 'cors'
import web from './web'
import http from 'http'
import cluster from 'cluster'
import os from 'os'
import dotenv from 'dotenv'

const fileUpload = require('express-fileupload')

dotenv.config()

const isTest = process.env.TEST
const PORT = isTest ? 8556 : 8555

function createWorkerProcess() {
  const worker = cluster.fork()
}

let app

if (!isTest && cluster.isMaster) {
  const cpuCount = os.cpus().length
  for (let i = 0; i < cpuCount; i++) {
    createWorkerProcess()
  }
} else {
  app = express()
  app.use(bodyParser.json({limit: '10mb'}))
  app.use(bodyParser.urlencoded({extended: true, limit: '50mb'}))
  app.use(cors())
  app.use(fileUpload())

  app.enable('trust proxy')

  app.set('views', './src/views/')
  app.use(express.static('public'))
  app.set('view engine', 'pug')

  app.use('/', web)
  app.use(handleExpressError)

  if (!isTest) {
    const server = http.createServer(app)
    server.listen(PORT, () => {
      console.log('Auth API listening on port ' + PORT)
    })
  }
}

cluster.on('exit', (worker) => {
  console.log(new Date(), 'Server process ', worker.id, ' exited!')
  createWorkerProcess()
})

export default app
